﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;


public class AnimationSplitWindow : EditorWindow {

	static private AnimationSplitWindow _instance;
	static private Vector2 windowSize = new Vector2(900, 600);
	static private Vector2 leftPartSize = new Vector2(300, 600);
	static private Vector2 rightPartSize = new Vector2(600, 600);
	
	private AnimationSplit utility;
	
	private string currentAnimation;

	private Vector2 animScrollPos;
	private Vector2 curveScrollPos;

	private bool selectAllCurvesFlag = false;

	[MenuItem("Custom/Animation Split")]
	static void Open () {
		if (_instance == null) {
			_instance = EditorWindow.GetWindow(typeof(AnimationSplitWindow), true, "Animation Split") as AnimationSplitWindow;
			_instance.minSize = new Vector2(900, 600);
			_instance.maxSize = new Vector2(900, 600);
		}
	}

	void OnEnable() {
		utility = new AnimationSplit();
		utility.GetAllAnimations(Application.dataPath);

	}

	void OnGUI() {
		GUILayout.BeginHorizontal();

		GUIAnimations();

		GUIAnimationCurves();

		GUILayout.EndHorizontal();
	}

	void GUIAnimations() {

		if (utility.animations != null) {
			animScrollPos = GUILayout.BeginScrollView(animScrollPos, false, true, GUILayout.Width(leftPartSize.x));
			foreach(string item in utility.animations) {
				if (GUILayout.Button(Path.GetFileNameWithoutExtension(item), GUILayout.Width(leftPartSize.x))) {
					if (currentAnimation != item) {
						utility.LoadCurves(item);
					}
					currentAnimation = item;
				}
			}
			GUILayout.EndScrollView();
		}
	}

	void GUIAnimationCurves() {

		if (null != utility.animInfos) {

			GUILayout.BeginVertical();

			GUITargetAnimationPath();


			GUILayout.BeginHorizontal();
			bool tmpFlag = GUILayout.Toggle(selectAllCurvesFlag, "Select All",GUILayout.Width(rightPartSize.x * 0.6f));
			if (tmpFlag != selectAllCurvesFlag) {
				utility.UpdateSelectInfo(tmpFlag);
				selectAllCurvesFlag = tmpFlag;
			}

			if (GUILayout.Button("export", GUILayout.Width(rightPartSize.x * .2f))) {
				utility.ExportClip();
			}
			GUILayout.EndHorizontal();

			curveScrollPos = GUILayout.BeginScrollView(curveScrollPos, false, true, GUILayout.Width(rightPartSize.x));

			foreach(AnimationClipData data in utility.animInfos) {
				GUILayout.BeginHorizontal();

				data.path  = GUILayout.TextField(data.path, GUILayout.Width(rightPartSize.x * 0.4f));
				data.property = GUILayout.TextField(data.property, GUILayout.Width(rightPartSize.x * 0.4f));
				data.selected = GUILayout.Toggle(data.selected, "", GUILayout.Width(rightPartSize.x * 0.2f));
				GUILayout.EndHorizontal();
			}

			GUILayout.EndScrollView();

			GUILayout.EndVertical();
		}
	}

	void GUITargetAnimationPath() {
		GUILayout.BeginHorizontal();

		GUILayout.Label("Target Animation : ", GUILayout.Width(rightPartSize.x * 0.3f));
		utility.targetPath = GUILayout.TextField(utility.targetPath, GUILayout.Width(rightPartSize.x * 0.7f));

		GUILayout.EndHorizontal();
	}


}
